// pages/login/login.js
const md5 = require('./md5.js');
const util = require('../../utils/util.js');
const wxPromisify = util.wxPromisify;
const wx_request_promisify = wxPromisify(wx.request);
const wx_login = wxPromisify(wx.login);
const wx_getUserInfo = wxPromisify(wx.getUserInfo);
const appid ='wxc04e0004ba280e4b';
let prefix = 'https://nmnhj9b.hk1.mofasuidao.cn/likai';
let header = {'content-type':'application/x-www-form-urlencoded'};
var app = getApp();
Page({
  onLoad: function (options) {    
    // 页面初始化 options为页面跳转所带来的参数
    var that = this;
    wx_login()
    .then((res) => {
       this.setData({ code: res.code });
       return wx_getUserInfo();
    }).then((res) => {
       this.setData({encryptedData: res.encryptedData})
       this.setData({ iv: res.iv })
       let url = `${prefix}/components/wxapplogin/open/isAccountExistedByWxapp.json`;
       return wx_request_promisify({
             url : url,
             method : 'POST',
             data : Object.assign({appId : appid},this.data),
             header : header
       })
      }).then((res) => {
        if(!res.data.success) return;
         wx.setStorageSync('thirdSessionId',res.data.data.thirdSessionId);  
         if(res.data.data.existed){
            wx.showLoading('加载中');
            //如果用户存在，直接登录
            return wx_request_promisify({
                url : prefix + '/login',
                header : Object.assign({Cookie : wx.getStorageSync('thirdSessionId')},header),
                method : 'POST',
                data : {
                    username: res.data.data.userInfo.uid,
                    password: "",
                    appId: appid,
                    login_ct: 'ajax',
                    client:'wxapp'                  
                }
            })
         }
      }).then((res) => {
          if(!res){
            this.setData({isLogin:true});
            return;
          } 
          //如果成功存在localStorage中
          if(res.data.success) {
            wx.setStorageSync('JSESSIONID', res.data.data.JSESSIONID);   
           wx.showToast({
              title: '成功',
              icon: 'success',
              duration: 2000,
              success: function (e) {
                wx.redirectTo({
                  url: '/pages/clazz/clazz'
                });
               }
            });         
          }else {
            wx.showToast({
                title: '登录失败',
                icon: 'warn',
                duration: 2000
              })            
          }
      }).catch(e => {
         //捕获promise错误；
          console.log(e);
      })       
  },
  onReady: function () {

  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  userInfo(res) {
    if (res.currentTarget.id === 'user_name') {
      this.setData({ phonenumber: res.detail.value })
    } else if (res.currentTarget.id === 'password') {
      this.setData({ password: res.detail.value })
    }
    this.data.phonenumber && this.data.password && this.setData({ isdisabled: false })
  },
  getCode() {
    wx_request_promisify({
      url: prefix + '/open/safetykey/getkey.json',
      method: 'GET'
    }).then(res => {
      return wx_request_promisify({
        url: prefix + '/plugins/sms/open/sendCaptcha.json',
        data: {
          "phonenumber": this.data.phonenumber,
          "bskeyid": res.data.data,
          "type": "1"
        },
        method: "GET"
      })
    }).then(res => {
      console.log(res)
    })
  },
  loginSubmit() {
    var that = this;
    if(!this.data.phonenumber) {
    wx.showToast({
      title: '账户不能为空',
      icon: 'success',
      duration: 2000
    })     
      return;
    }
    wx.showLoading('加载中');
    wx_request_promisify({
      url: prefix + '/components/wxapplogin/open/autoRegistByWxapp.json',
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': 'JSESSIONID=' + wx.getStorageSync('thirdSessionId')
      },
      method: 'POST',
      data: {
        username: this.data.phonenumber,
        password: md5.hexMD5(this.data.password),
        appId: appid,
        login_ct: 'ajax'
      }
    }).then(res =>{
      if(res.statusCode >= 200 && res.statusCode <= 300 || res.statusCode === 304){
                 wx.redirectTo({
                  url: '/pages/clazz/clazz'
                });       
      }else {
          wx.hideLoading();
          wx.showToast({
            title: '登录失败',
            image: '../../images/error.png',
            duration: 2000
          })          
      }
    }).catch((e) => {
        
    });
  }
})